<?php

namespace App\Http\Controllers\Admin;

use App\Models\AuthGroupAccess;
use App\Models\Brand;
use App\Models\GoodsCategory;
use App\Models\Notice;
use App\Models\Picture;
use App\Models\Service;
use App\Models\Shop;
use App\Models\ShopAccount;
use App\Models\ServiceCharge;
use App\Models\WechatSet;
use App\Models\WxPay;
use QrCode;

/**
 * 店铺管理控制器
 */
class ShopController extends BaseController
{

    public function __construct(
        Shop $shop,
        GoodsCategory $goodsCategory,
        Brand $brand,
        Picture $picture,
        Notice $notice,
        WxPay $wxPay,
        ServiceCharge $serviceCharge,
        Service $service,
        AuthGroupAccess $authGroupAccess,
        ShopAccount $shopAccount,
        WechatSet $wechatSet
    )
    {
        parent::__construct();
        $this->shop = $shop;
        $this->goodsCategory = $goodsCategory;
        $this->brand = $brand;
        $this->picture = $picture;
        $this->notice = $notice;
        $this->wxPay = $wxPay;
        $this->serviceCharge = $serviceCharge;
        $this->service = $service;
        $this->authGroupAccess = $authGroupAccess;
        $this->shopAccount = $shopAccount;
        $this->wechatSet = $wechatSet;
    }


    public function getIndex()
    {
        $rows = $this->shop->getShopList();
        return view('admin.shop.index', compact('rows'));
    }

    public function getInfo()
    {
        $info = $this->shop->_getOneById(request('id'));
        return view('admin.shop.info', compact('info'));
    }

    public function getOwn()
    {
        $rows = $this->shop->getShopList();
        return view('admin.shop.index', compact('rows'));
    }

    /* 新增分类 */
    public function getAdd()
    {
        return view('admin.shop.edit');
    }

    public function postAdd()
    {
        $res = $this->shop->addOrUpdate();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '新增失败');
        }
        return $this->success('新增成功', urlAdmin('shop', 'getIndex'));
    }

    /* 编辑分类 */
    public function getEdit()
    {
        $info = $this->shop->_getOneById(request('id'));
        return view('admin.shop.edit', compact('info'));
    }

    public function postEdit()
    {
        $res = $this->shop->addOrUpdate();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('shop', 'getIndex', ['pid' => request('pid')]));
    }

    /* 编辑分类 */
    public function getSetting()
    {
        $shop_id = request('id');
        $admin_id = request('admin_id');
        $info = $this->shop->_getOneById(request('id'));
        $ext = $this->picture->config['saveExt'];
        return view('admin.shop.setting_map', compact('info', 'ext', 'shop_id', 'admin_id'));
    }

    public function postSetting()
    {
        $res = $this->shop->setting();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('设置成功', urlAdmin('shop', 'getIndex', ['pid' => request('pid')]));
    }

    public function getSliders()
    {
        $shop_id = request('id');
        $admin_id = request('admin_id');
        $info = $this->shop->_getOneById(request('id'));
        $ext = $this->picture->config['saveExt'];
        return view('admin.shop.slider', compact('info', 'ext', 'shop_id', 'admin_id'));
    }

    public function postSliders()
    {
        $res = $this->shop->saveSliders();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('保存成功', urlAdmin('shop', 'getIndex', ['pid' => request('pid')]));
    }

    public function anySetStatus()
    {
        $ids = is_array(request('ids')) ? request('ids') : [request('ids')];
        $status = request('status');
        if (empty($ids)) {
            return $this->error('请选择要操作的数据');
        }
        $where['id'] = ['in', $ids];
        switch ($status) {
            case -1 :
                $this->shop->_redisGenerateByIds($ids);
                return $this->delete($this->shop, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 0  :
                $this->shop->_redisGenerateByIds($ids);
                return $this->forbid($this->shop, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                $this->shop->_redisGenerateByIds($ids);
                return $this->resume($this->shop, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default :
                return $this->error('参数错误');
        }
    }

    public function getNotice()
    {
        $shop_id = request('id');
        $admin_id = request('admin_id');
        $info = $this->notice->_redisGetOneBySid($shop_id);
        return view('admin.shop.notice', compact('info', 'shop_id', 'admin_id'));
    }

    public function postNotice()
    {
        $res = $this->notice->addOrUpdate();
        if (!$res) {
            return $this->error($this->notice->getError() ? $this->notice->getError() : '未知错误');
        }
        return $this->success('设置成功', urlAdmin('shop', 'getIndex'));
    }


    public function getCharge()
    {
        $shopId = request('id');
        if (!$shopId) {
            return $this->error('非法操作');
        }
        $shopInfo = $this->shop->_redisGetOneBySid($shopId);
        $step = request('step', 1);
        if ($step == 1) {
            $accessInfo = $this->authGroupAccess->_getOne(['aid' => $shopInfo['admin_id']]);
            if (!$accessInfo) {
                $accessInfo['group_id'] = 3;
            }
            $serviceInfo = $this->service->_getOne(['group_id' => $accessInfo['group_id']]);
            return view('admin.shop.charge_step1', compact('shopInfo', 'serviceInfo'));
        }
        if ($step == 2) {
            $accessInfo = $this->authGroupAccess->_getOne(['aid' => $shopInfo['admin_id']]);
            if (!$accessInfo) {
                $accessInfo['group_id'] = 3;
            }
            $serviceInfo = $this->service->_getOne(['group_id' => $accessInfo['group_id']]);
            $order = $this->serviceCharge->addOrder($shopInfo, $serviceInfo);
            if (!$order) {
                return $this->error($this->serviceCharge->getError());
            }
            $aid = 1;
            $wechatInfo = $this->wechatSet->_getOne(['admin_id' => $aid]);
            $config = [
                'appid' => $wechatInfo['wx_app_id'],
                'pay_mchid' => $wechatInfo['mch_id'],
                'pay_apikey' => $wechatInfo['mch_key'],
                'notify_url' => urlAdmin('shop', 'anyChargeNotify'),
                'body' => '续费订单编号:' . $order['order_sn']
            ];
            $this->wxPay->setConfig($config);
            $payArr['body'] = $config['body'];
            $payArr['order_sn'] = $order['order_sn'];
            $payArr['total_fee'] = $order['order_amount'];
            $result = $this->wxPay->prepay($payArr, 1);
            if (!$result) {
                return $this->error($this->wxPay->getError() ? $this->wxPay->getError() : '未知错误');
            }
            $img = QrCode::size(298)->generate($result);
            return view('admin.shop.charge_step2', compact('shopInfo', 'img', 'order'));
        }
        if ($step == 3) {
            return view('admin.shop.charge_step3');
        }
    }

    public function anyChargeNotify()
    {
        $res = $this->wxPay->notify(3);
//        if ($res) {
//            //更新数据库水票相关数据
//            $this->shopCharge->dealOrder($res['out_trade_no']);
//        }
    }

    public function getCheckOrderStatus()
    {
        $orderId = request('id');
        if (!$orderId) {
            return error('非法操作');
        }
        $res = $this->serviceCharge->_getOneById($orderId);
        if (!$res) {
            return error('订单不存在');
        }
        if ($res['status'] == 20) {
            addSession('show_notice', '');
            return success();
        }
        return error();
    }

    public function getChargeRecord()
    {
        $rows = $this->serviceCharge->getRecord();
        return view('admin.shop.charge_record', compact('rows'));
    }

    public function getAccount()
    {
        $sid = request('shop_id');
        $aid = request('admin_id');
        $shop = $this->shop->_getOneById($sid);
        if (!$shop) {
            return error('店铺不存在');
        }
        if ($shop['admin_id'] != $aid && !is_administrator()) {
            return error('非法操作');
        }

        $info = $this->shop->_getOneById($sid);
        return view('admin.shop.account', compact('info'));
    }

    public function postAccount()
    {
        $res = $this->shop->saveAccount();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('shop', 'getIndex'));
    }

}
